package com.sanerzone.smscenter.biz.listener;

import com.alibaba.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import com.alibaba.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import com.alibaba.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import com.alibaba.rocketmq.common.message.MessageExt;
import com.sanerzone.common.support.utils.FstObjectSerializeUtil;
import com.sanerzone.smscenter.biz.mapper.SmsWhiteListMapper;
import com.sanerzone.smscenter.biz.message.SMSMOMessage;
import com.sanerzone.smscenter.biz.message.SMSWLMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class SMSWLListener implements MessageListenerConcurrently{

    public static Logger logger = LoggerFactory.getLogger(SMSWLListener.class);
    @Autowired
    private SmsWhiteListMapper smsWhiteListMapper;

    @Override
    public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) {
        try{
            for (MessageExt msg: msgs) {//遍历
                if (msg.getReconsumeTimes() > 2 ) {
                    continue;
                }
                logger.info("WL listener recv message: topic:{}, tags:{}, msgid:{}, key:{}", msg.getTopic(), msg.getTags(),
                        msg.getMsgId(), msg.getKeys());
                SMSWLMessage smswlMessage= (SMSWLMessage) FstObjectSerializeUtil.read(msg.getBody());

                if(smswlMessage != null ){
                    smsWhiteListMapper.insert( smswlMessage );
                } else {
                    logger.info("WL listener recv message: topic:{}, tags:{}, msgid:{}, key:{}", msg.getTopic(), msg.getTags(),
                            msg.getMsgId(), msg.getKeys());
                    return ConsumeConcurrentlyStatus.RECONSUME_LATER;
                }
            }


        }catch (Exception e){
            logger.error("INSMSWL-ERR", e);
        }
        return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
    }
}
